import React, { useState } from 'react';
import { Button, Modal, Popconfirm, Select, Input, Form, Radio, Card, message, Table } from 'antd';
import { getUserList, IUser, addUserApi, roleTypes, updateUserApi, deleteUserApi } from 'api/User';
import Breadcrumb from 'components/common/Breadcrumb';
import './index.less';
import { useAntdTable, useRequest } from 'ahooks';
import { getAllArea, IArea } from 'api/Area';
import { PlusOutlined } from '@ant-design/icons';
import { PaginatedParams } from 'ahooks/lib/useAntdTable';
const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
};
const UserManage = () => {
    const { data: areas = [] } = useRequest(getAllArea);
    const [visible, setVisible] = useState(false);
    const [userInEdit, setUserInEdit] = useState<IUser>();
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
        },
        {
            title: '账号ID',
            dataIndex: 'username',
        },
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '手机',
            dataIndex: 'mobile',
        },
        {
            title: '账号类型',
            dataIndex: 'role',
            render: (role: number) => <span>{roleTypes[role]}</span>,
        },
        {
            title: '负责区域',
            dataIndex: 'areaId',
            render: (text: any) => <span>{areas.find((item) => item.id === text)?.name || '全部区域'}</span>,
        },
        {
            title: '配置时间',
            dataIndex: 'createTime',
        },
        {
            title: '操作',
            render: ({}, record: any) => (
                <>
                    <Button size="small" onClick={() => editUser(record)} className="mr10">
                        编辑
                    </Button>
                    <Popconfirm
                        title="删除后，该账号将无法登陆，是否继续？"
                        okText="确定"
                        cancelText="取消"
                        onConfirm={() => deleteUser(record)}
                    >
                        <Button danger size="small" className="mr10" disabled={record.id === 1}>
                            删除
                        </Button>
                    </Popconfirm>
                    <Popconfirm
                        title="密码将恢复成系统默认 000000, 是否继续？"
                        okText="确定"
                        cancelText="取消"
                        onConfirm={() => resetPassword(record)}
                    >
                        <Button size="small">密码重置</Button>
                    </Popconfirm>
                </>
            ),
        },
    ];
    const { run: addUserRun, loading: addUserLoading } = useRequest(addUserApi, {
        manual: true,
    });
    const { run: updateUserRun, loading: updateUserLoading } = useRequest(updateUserApi, {
        manual: true,
    });
    /** 编辑账号 */
    const editUser = (user: IUser) => {
        setVisible(true);
        const { username, name, mobile, areaId, salt, role } = user;
        form.setFieldsValue({
            username,
            name,
            mobile,
            areaId,
            password: salt,
            role,
        });
        setUserInEdit(user);
    };
    /** 删除用户 */
    const deleteUser = (record: IUser) => {
        deleteUserApi([record.id]).then(() => {
            message.success('删除用户成功')
        })
        reset()
    };
    /** 密码重置 */
    const resetPassword = async (record: IUser) => {
        await updateUserApi({ ...record, password: '000000' })
        message.success('密码重置成功')
        reset()
    };
    
    /** 表单初始化 */
    const [form] = Form.useForm();
    /** 添加用户 */
    const addUser = () => {
        setUserInEdit(undefined);
        form.resetFields();
        form.setFieldsValue({ password: '000000' })
        setVisible(true);
    };
    const onOk = async () => {
        const res = await form.validateFields();
        console.log(res);
        let newUser: any = {
            ...res,
            status: 1,
            email: 'test@qq.com'
        };
        if (userInEdit) {
            newUser = {
                ...userInEdit,
                ...newUser,
            };
            updateUserRun(newUser).then(() => {
                setVisible(false);
                message.success('更新用户成功');
                reset()
            });
        } else {
            addUserRun(newUser).then(() => {
                setVisible(false);
                message.success('添加用户成功');
                reset()
            });
        }
    };
    const onCancel = () => {
        setVisible(false);
    };
    const setDefaultPassword = () => {
        form.setFields([{ name: 'password', value: '000000' }]);
    };

    const [queryForm] = Form.useForm()
    const getTableData = (
        { current, pageSize }: PaginatedParams[0],
        formData: any,
    ) => {
        console.log(formData)
        const query = {
            current,
            pageSize,
            ...formData
        }
        return getUserList(query).then((res) => ({
            total: res.totalCount,
            list: res.list.map((item: any, index: number )=> ({ index: index + 1 + (current - 1) * pageSize, ...item }))
        }));
    };
    const { tableProps, search } = useAntdTable(getTableData, {
        defaultPageSize: 5,
        form: queryForm,
    });

    const { submit, reset } = search;

    return (
        <div className="user-manage">
            <Breadcrumb crumbs={['路桩配置', '添加路桩']}></Breadcrumb>
            <div className="flex-between mb10">
                <Button onClick={addUser} type="primary">
                    <PlusOutlined />
                    添加账号
                </Button>
                <Form form={queryForm} layout="inline">
                    <Form.Item label="账号类型" name="role">
                        <Select placeholder="请选择" style={{ width: 150 }} allowClear>
                            <Select.Option value={0}>普通账号</Select.Option>
                            <Select.Option value={1}>管理员账号</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item name="keyword">
                        <Input placeholder="支持账号ID、管理员姓名、手机号查询" style={{ width: 300 }} allowClear></Input>
                    </Form.Item>
                    <Button onClick={submit}>查询</Button>
                </Form>
            </div>
            <Table columns={columns} rowKey="id" {...tableProps} />
            <Modal
                title={userInEdit ? '编辑用户' : '添加用户'}
                visible={visible}
                onOk={onOk}
                onCancel={onCancel}
                okText="确定"
                cancelText="取消"
                okButtonProps={{ disabled: addUserLoading || updateUserLoading }}
            >
                <Form {...layout} form={form}>
                    <Form.Item label="用户ID" name="username" rules={[{ required: true, message: '请输入用户ID' }]}>
                        <Input placeholder="请输入用户ID" allowClear />
                    </Form.Item>
                    <Form.Item label="初始密码">
                        <Form.Item
                            name="password"
                            rules={[{ required: true, message: '请输入用户密码' }]}
                            style={{ display: 'inline-block', marginBottom: 0 }}
                        >
                            <Input
                                type="password"
                                placeholder="支持6~15位数字或字母"
                                className="mr10"
                                style={{ width: 266 }}
                                allowClear
                            />
                        </Form.Item>
                        <Button onClick={setDefaultPassword} title="000000">系统默认密码</Button>
                    </Form.Item>
                    <Form.Item label="姓名" name="name" rules={[{ required: true, message: '请输入姓名' }]}>
                        <Input placeholder="请输入姓名" allowClear />
                    </Form.Item>
                    <Form.Item label="手机号" name="mobile" rules={[{ required: true, message: '请输入手机号' }]}>
                        <Input placeholder="请输入手机号" allowClear />
                    </Form.Item>
                    <Form.Item label="负责区域" name="areaId" rules={[{ required: true, message: '请选择负责区域' }]}>
                        <Select>
                            <Select.Option value={0}>全部区域</Select.Option>
                            {areas.map((area: IArea) => (
                                <Select.Option key={area.id} value={area.id || ''}>
                                    {area.name}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item label="账号类型" name="role" rules={[{ required: true, message: '请选择账号类型' }]}>
                        <Radio.Group>
                            <Radio value={0}>普通账号</Radio>
                            <Radio value={1}>管理员账号</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Card style={{ color: '#1890ff'}}>
                        <p>账号类型说明</p>
                        <p>普通账号：仅可管控负责区域的路桩，无法修改系统配置</p>
                        <p>管理员账号：可全局配置系统及查看所有路桩状态</p>
                    </Card>
                </Form>
            </Modal>
        </div>
    );
};
export default UserManage;
